from aiogram import Bot, F, Router
from aiogram.fsm.context import FSMContext
from aiogram.types import CallbackQuery

from factories import get_ProScreen, get_screen
from mytypes import CB_button, CB_buy_pro, CB_screen, CB_video
from sessions import user_sessions
from settings import settings
from utils import alert_admin, debugger, log

from .form_antiklesh import start_form_antiklesh


# remove recent video
async def _remove_video_layer(user_id: int, bot: Bot):
    """Utility function to clear Video Layer"""
    # get current session
    session = user_sessions.get(user_id, {})
    # check if video was sended
    video_layer = session.get("VideoLayerID", None)
    if video_layer:
        # remove last video from video lauer
        await bot.delete_message(chat_id=user_id, message_id=video_layer)
        debugger.info("VideoLayer очищен")
        session["VideoLayerID"] = None
    # update session
    user_sessions[user_id] = session


router = Router()


@router.callback_query(CB_screen.filter())
async def _menu_content(call: CallbackQuery, bot: Bot, callback_data: CB_screen):
    # get path
    path = callback_data.path
    # get screen by path
    screen = get_screen(path)
    # clear Video Layer
    await _remove_video_layer(call.from_user.id, bot)
    if bool(screen):
        # send new screen to user
        await call.message.edit_text(screen.content, reply_markup=screen.keyboard)
        debugger.info(f"Edit message with screen {path}")
    else:
        log.warning(f"Screen not found {path}")
    await call.answer()


@router.callback_query(CB_video.filter())
async def _menu_video_content(call: CallbackQuery, bot: Bot, callback_data: CB_video):
    # sugar
    user_id = call.from_user.id
    # get session
    session = user_sessions.get(user_id, {})
    # read PATH from callback row
    path = callback_data.path
    # get screen by path
    screen = get_screen(path)
    if bool(screen):
        # clear Video Layer
        await _remove_video_layer(user_id, bot)
        # check if PROD or STG mode
        video_source = (
            screen.video_id
            if settings.is_prod
            else "CgACAgIAAxkBAAIBQ2XQFXMyg1z__haBUjB-4wHE4cnXAAK-SgAC_lmASnc9CAdH0sI-NAQ"
        )
        # check if user has access to video
        if session.get("is_pro"):
            # send video to user
            new_message = await bot.send_video(
                chat_id=user_id,
                video=video_source,
                caption=screen.vide_title,
                protect_content=True,
            )
            debugger.info(f"Send video [{screen.vide_title}] {video_source}")
        else:
            screen = get_ProScreen(user_id)
            # send 'buy PRO screen'
            new_message = await bot.send_message(
                chat_id=user_id,
                text=screen.content,
                reply_markup=screen.keyboard,
                protect_content=True,
            )
            debugger.info("Send 'buy PRO' screen")
        # put new Video Layer to session
        session["VideoLayerID"] = new_message.message_id
    else:
        log.warning(f"Screen not found {path}")

    await call.answer()
    # update session
    user_sessions[user_id] = session


@router.callback_query(CB_buy_pro.filter())
async def _menu_buy_pro(call: CallbackQuery, bot: Bot, callback_data: CB_buy_pro):
    user_id = call.from_user.id
    if callback_data.user_id == user_id:
        session = user_sessions.get(user_id, {})
        await alert_admin(
            bot,
            f"<b>[Покупка PRO]</b>\n@{call.from_user.username} ({user_id})",
        )
        debugger.info(f"Buy PRO user: {user_id}")
        session["is_pro"] = 1
        await call.message.edit_text(
            "\n".join(
                [
                    "Поздравляем, PRO аккаунт куплен!",
                    "Теперь Вы можете пользоваться ботом без ограничений.",
                ]
            ),
            reply_markup=None,
        )
    else:
        log.warning(f"[Buy PRO HACK] user: {user_id} but in data {data.get('user_id')}")
    await call.answer()


@router.callback_query(CB_button.filter())
async def _start_form(call: CallbackQuery, callback_data: CB_button, state: FSMContext):
    await start_form_antiklesh(message=call.message, state=state)